/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.anny.shop.web;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.beans.ResultBean;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.anny.shop.entity.AnnyShopCategory;
import com.jeeplus.modules.anny.shop.service.AnnyShopCategoryService;

/**
 * 用于店铺的分类Controller
 * @author xy
 * @version 2018-12-03
 */
@Controller
@RequestMapping(value = "${adminPath}/anny/shop/annyShopCategory")
public class AnnyShopCategoryController extends BaseController {

	@Autowired
	private AnnyShopCategoryService annyShopCategoryService;
	
	@ModelAttribute
	public AnnyShopCategory get(@RequestParam(required=false) String id) {
		AnnyShopCategory entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = annyShopCategoryService.get(id);
		}
		if (entity == null){
			entity = new AnnyShopCategory();
		}
		return entity;
	}
	
	/**
	 * 店铺分类列表页面
	 */
	@RequiresPermissions("anny:shop:annyShopCategory:list")
	@RequestMapping(value = {"list", ""})
	public String list(AnnyShopCategory annyShopCategory, Model model) {
		model.addAttribute("productCategory", annyShopCategory);
		return "modules/anny/shop/annyShopCategoryList";
	}
	
		/**
	 * 店铺分类列表数据
	 */
	@ResponseBody
	@RequiresPermissions("anny:shop:annyShopCategory:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(AnnyShopCategory annyShopCategory, HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			request.setCharacterEncoding("utf-8");
			annyShopCategory.setName(new String(request.getParameter("name").getBytes("iso8859-1"),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Page<AnnyShopCategory> page = annyShopCategoryService.findPage(new Page<AnnyShopCategory>(request, response), annyShopCategory); 
		return getBootstrapData(page);
	}
	
	/**
	 * 获取类别
	 * @param annyShopCategory
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "categoryData")
	public ResultBean<List<AnnyShopCategory>> categoryData(AnnyShopCategory annyShopCategory) {
		ResultBean<List<AnnyShopCategory>> result = new ResultBean<>();
		logger.info("++++++++通过类别开始++++++++");
		List<AnnyShopCategory> list = annyShopCategoryService.findList(annyShopCategory);
		result.setData(list);
		if(list != null && list.size() > 0){
			result.setCode(ResultBean.SUCCESS);
			result.setMsg("获取数据成功");
		}else{
			result.setCode(ResultBean.NO_LOGIN);
			result.setMsg("数据库无数据");
		}
		logger.info("++++++++通过类别结束++++++++");
		return result;
	}
	/**
	 * 根据id来获取商品的类别
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getShopCategoryById")
	public ResultBean<AnnyShopCategory> getShopCategoryById(String id){
		ResultBean<AnnyShopCategory> result = new ResultBean<>();
		logger.info("++++++++通过id获取店铺类别开始++++++++");
		AnnyShopCategory shopCategory = annyShopCategoryService.get(id);
		result.setData(shopCategory);
		if(null != shopCategory){
			result.setMsg("获取数据成功");
			result.setCode(ResultBean.SUCCESS);
		}else{
			result.setMsg("数据库暂无数据");
		}
		logger.info("++++++++通过id获取店铺类别结束++++++++");
		return result;
	}

	/**
	 * 查看，增加，编辑店铺分类表单页面
	 */
	@RequiresPermissions(value={"anny:shop:annyShopCategory:view","anny:shop:annyShopCategory:add","anny:shop:annyShopCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(AnnyShopCategory annyShopCategory, Model model) {
		model.addAttribute("annyShopCategory", annyShopCategory);
		if(StringUtils.isBlank(annyShopCategory.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/anny/shop/annyShopCategoryForm";
	}

	/**
	 * 保存店铺分类
	 */
	@RequiresPermissions(value={"anny:shop:annyShopCategory:add","anny:shop:annyShopCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(AnnyShopCategory annyShopCategory, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, annyShopCategory)){
			return form(annyShopCategory, model);
		}
		//新增或编辑表单保存
		annyShopCategoryService.save(annyShopCategory);//保存
		addMessage(redirectAttributes, "保存店铺分类成功");
		return "redirect:"+Global.getAdminPath()+"/anny/shop/annyShopCategory/?repage";
	}
	
	/**
	 * 删除店铺分类
	 */
	@ResponseBody
	@RequiresPermissions("anny:shop:annyShopCategory:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(AnnyShopCategory annyShopCategory, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		annyShopCategoryService.delete(annyShopCategory);
		j.setMsg("删除店铺分类成功");
		return j;
	}
	
	/**
	 * 批量删除店铺分类
	 */
	@ResponseBody
	@RequiresPermissions("anny:shop:annyShopCategory:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			annyShopCategoryService.delete(annyShopCategoryService.get(id));
		}
		j.setMsg("操作完成，存在商品的类别将无法被删除！");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("anny:shop:annyShopCategory:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(AnnyShopCategory annyShopCategory, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "店铺分类"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<AnnyShopCategory> page = annyShopCategoryService.findPage(new Page<AnnyShopCategory>(request, response, -1), annyShopCategory);
    		new ExportExcel("店铺分类", AnnyShopCategory.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出店铺分类记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("anny:shop:annyShopCategory:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<AnnyShopCategory> list = ei.getDataList(AnnyShopCategory.class);
			for (AnnyShopCategory annyShopCategory : list){
				try{
					annyShopCategoryService.save(annyShopCategory);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条店铺分类记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条店铺分类记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入店铺分类失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/anny/shop/annyShopCategory/?repage";
    }
	
	/**
	 * 下载导入店铺分类数据模板
	 */
	@RequiresPermissions("anny:shop:annyShopCategory:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "店铺分类数据导入模板.xlsx";
    		List<AnnyShopCategory> list = Lists.newArrayList(); 
    		new ExportExcel("店铺分类数据", AnnyShopCategory.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/anny/shop/annyShopCategory/?repage";
    }

}